<template>
  <view class="address-bar" :style="'height: '+height+'rpx'" @click="toSelect">
    <image class="icon" src="/static/images/icon/icon_address.png" mode="aspectFit" />
    <view class="sub-item">
      <template v-if="loading">加载中</template>
      <template v-else-if="address.id">
        <view class="address">{{ address.areaName+address.address }}</view>
        <view>{{ address.consignee }}<text>{{ address.mobile }}</text></view>
      </template>
      <template v-else>请选择收货地址</template>
    </view>
    <image class="icon" src="/static/images/icon/icon_arrow_right_disabled.png" mode="aspectFit" />
    <slot></slot>
  </view>
</template>
<script>
import { mapState } from 'vuex'
export default {
  name: 'AddressBar',
  props: {
    address: {
      type: Object,
      default() {
        return {} // 已选地址数据
      }
    },
    select: {
      type: Boolean,
      default: true // 点击是否跳转选择收货地址
    },
    height: {
      type: Number,
      default: 100 // 高度
    }
  },
  data() {
    return {
      loading: false
    }
  },
  computed: {
    ...mapState([
      'token'
    ])
  },
  created() {
    if (!this.address.id && this.token) { // 未选择收货地址且已登录的时候去获取默认收货地址
      this.fetchData()
    }
  },
  methods: {
    toSelect() {
      this.$emit('click')
      if (this.select) {
        this.$navigateTo('/pagesMine/address/address?type=select')
      }
    },
    async fetchData() {
      this.loading = true
      const res = await this.$api.mineApi.getAddressList()
      if (res.success) {
        if (res.data && res.data.length) {
          let result = {}
          const data = res.data.filter(i => i.isDefault)
          if (data.length) {
            result = data[0]
          } else {
            result = res.data[0]
          }
          this.$emit('change', result)
        }
      }
      this.loading = false
    }
  }
}
</script>
<style lang="scss">
.address-bar{
  @include flex-container;
  @include a-center;
  padding: 0 20rpx;
  border: 1px solid rgb(230, 230, 230);
  border-radius: 20rpx;
  position: relative;

  .icon{
    width: 30rpx;
    height: 30rpx;
  }
  .sub-item{
    color: #999;
    font-size: 28rpx;
    text-align: left;
    padding: 0 10rpx;

    .address{
      @include text-ellipsis;
      color: #000;
      margin-bottom: 6rpx;
    }
    text{
      padding-left: 12rpx;
    }
  }
}
</style>
